package com.hnit.applet.utils;

import com.alibaba.fastjson.JSONObject;
import com.hnit.applet.entity.OnlyOfficeDo;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author zwj
 * @date 2022/6/16
 * @description TODO onlyoffice工具类
 */

@Component
@RefreshScope
public class OnlyOfficeUtil {

    @Resource
    private RestTemplate restTemplate;

    @Value("${url.onlyoffice}")
    private String onlyOfficeUrl;

    @Value("${url.downloadUrl}")
    private String downloadUrl;

    /**
     * @param inputType         待转换文件格式
     * @param downloadInterface 待转换文件下载接口
     * @param outputType        转换之后的文件格式
     *
     * @return 转换之后的文件字节数组
     */
    public byte[] conversion(String inputType, String downloadInterface, String outputType) throws Exception {
        String url = onlyOfficeUrl + "/ConvertService.ashx";
        Map<String, Object> map = new HashMap<>(16);
        map.put("async", false);
        map.put("filetype", inputType);
        map.put("key", UUID.randomUUID().toString().replace("-", ""));
        map.put("outputtype", outputType);
        map.put("title", "");
        map.put("url", downloadUrl + downloadInterface);
        ResponseEntity<String> response1 = restTemplate.postForEntity(url, map, String.class);
        OnlyOfficeDo onlyOfficeResult = JSONObject.parseObject(response1.getBody(), OnlyOfficeDo.class);
        if (onlyOfficeResult != null && StringUtils.isNotBlank(onlyOfficeResult.getError())) {
            String msg;
            switch (onlyOfficeResult.getError()) {
                case "-2":
                    msg = "转换超时错误";
                    break;
                case "-3":
                    msg = "转换错误";
                    break;
                case "-4":
                    msg = "下载要转换的文档文件时出错";
                    break;
                case "-5":
                    msg = "密码错误";
                    break;
                case "-6":
                    msg = "访问转换结果数据库时出错";
                    break;
                case "-7":
                    msg = "输入错误";
                    break;
                case "-8":
                    msg = "令牌无效";
                    break;
                default:
                    msg = "未知错误";
            }
            throw new Exception();
        }
        if (onlyOfficeResult != null && StringUtils.isNotBlank(onlyOfficeResult.getFileUrl())) {
            try {
                URL pdfUrl = new URL(onlyOfficeResult.getFileUrl());
                HttpURLConnection con = (HttpURLConnection) pdfUrl.openConnection();
                con.setConnectTimeout(5 * 1000);
                InputStream inputStream = con.getInputStream();
                byte[] bytes = IOUtils.toByteArray(inputStream);
                inputStream.close();
                return bytes;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
